<template>
	<div class="mt-13">
		<base-text textT="reset.step3Title" class="text-lg" block></base-text>
		<base-input :label="$t('account.password')" type="password" v-model="password" />
		<base-input-rule :title="$t('register.passwordRuleTitle')" :options="passwordRule" />
		<div class="mt-10 p-1">
			<base-button type="primary" :disabled="passwordInvalid" :loading="loading" @click="onSubmit">
				{{ $t('reset.submit') }}
			</base-button>
		</div>
	</div>
</template>
<script lang="ts" setup>
import { BaseButton, BaseInput, BaseInputRule, BaseText } from '@/components/base'
import { computed, inject, ref, Ref } from 'vue'
import { hasSpace, isLength, isPassword, t } from '@/utils'
import { useRequest } from '@/hooks'
import { useAppStore } from '@/store'
import { DeviceType } from '@/enums'
import { CodeParams } from '@/types'
import { resetPassword } from '@/api/account.ts'

const params = inject<Ref<CodeParams>>('params')

const emits = defineEmits(['success'])

const appStore = useAppStore()

const password = ref('')

const passwordRule = computed(() => {
	return [
		{
			textT: 'register.passwordRuleLength',
			valid: isLength(password.value.trim(), 6, 20)
		},
		{ textT: 'register.passwordRuleChar', valid: isPassword(password.value) },
		{ textT: 'register.passwordRuleSpace', valid: !hasSpace(password.value) }
	]
})

const passwordInvalid = computed(() => passwordRule.value.some(({ valid }) => !valid))

const { loading, run } = useRequest(resetPassword, {
	showSuccess: t('reset.success'),
	showError: true,
	onSuccess: () => emits('success')
})

const onSubmit = () => {
	if (!appStore.uuid) {
		appStore.setUUID()
	}
	run({
		...params?.value,
		deviceType: DeviceType.pc,
		deviceId: appStore.uuid,
		password: password.value.trim()
	})
}
</script>
